<script setup lang="ts">
import { useRequest } from 'vue-request'
import { useUserInfoStore } from '@/store/userInfo'
import avatarPlaceholder from '@/static/images/profile/avatar_placeholder.png'
import { fetchMyCouponListAPI } from '@/apis/fetchMyCouponList'
import { useGeneralDataStore } from '@/store/generalData'
import dialogIcon from '@/static/images/phone_colorful.png'
import { uploadFileAPI } from '@/apis/uploadFile'
import { updateProfileAPI } from '@/apis/updateProfile'
import { useRouterGuards } from '@/composables/useRouterGuards'
import { fetchDistributionListAPI } from '@/apis/fetchDistributionList'

const router = useRouter()
const routerGuards = useRouterGuards()
const userInfoStore = useUserInfoStore()
const generalDataStore = useGeneralDataStore()
const myCouponCount = ref(0)
const isShowDialog = ref(false)
const isShowCompletionDialog = ref(false)

const { data: distributionMoney } = useRequest(
  () => fetchDistributionListAPI({
    page: '1',
    limit: '9999',
  }, userInfoStore.userInfo!.token).then(res => res.data?.data.total),
)

onLoad(() => {
  if (!uni.getStorageSync('profileCompleted') && userInfoStore.userInfo?.nickname === '微信用户') {
    isShowCompletionDialog.value = true
    uni.setStorageSync('profileCompleted', true)
  }
})

onShow(() => {
  userInfoStore.update()
  getMyCouponCount()
})

async function getMyCouponCount() {
  if (userInfoStore.userInfo?.token) {
    const res = await fetchMyCouponListAPI({ page: '1', limit: '9999', type: '1' }, userInfoStore.userInfo!.token!)
    if (res.data?.code === 1)
      myCouponCount.value = res.data.data.data.filter(el => el.id).length
    else
      uni.showToast({ title: res.data?.msg, icon: 'none' })
  }
}

function handleSetProfile() {
  routerGuards(() => {
    router.push('profileSettings')
  })
}

function handleTapQRCode() {
  routerGuards(() => {
    router.push('profileQRCode')
  })
}

function handleViewDistribution() {
  routerGuards(() => {
    router.push('distributionList')
  })
}

function handleViewPointsMall() {
  routerGuards(() => {
    router.push('pointsMall')
  })
}

function handleViewMyCouponList() {
  routerGuards(() => {
    router.push('myCouponList')
  })
}

function handleTapRecord() {
  routerGuards(() => {
    router.push('record')
  })
}

function handleTapRedeemRecord() {
  routerGuards(() => {
    router.push('redeemRecord')
  })
}

function handleTapInviteRecord() {
  routerGuards(() => {
    router.push('inviteRecord')
  })
}

function handleTapMedicalAdvice() {
  routerGuards(() => {
    router.push('medicalAdviceList')
  })
}

function handleTapSettings() {
  routerGuards(() => {
    router.push('settings')
  })
}

function handleTapCouponList() {
  routerGuards(() => {
    router.push({
      name: 'couponList',
      params: { type: '领券中心' },
    })
  })
}

function handleTapOfficalAccount() {
  routerGuards(() => {
    router.push('officalAccount')
  })
}

function handleCall() {
  isShowDialog.value = false
  uni.makePhoneCall({
    phoneNumber: generalDataStore.generalData?.mobile || '',
    fail: () => { uni.showToast({ title: '取消呼叫', icon: 'none' }) },
  })
}

function handleContact() {}

const handleChooseAvatar = useThrottleFn(async (e: any) => {
  const url = e.detail.avatarUrl
  try {
    const res = await uploadFileAPI({ tempFilePath: url, fileType: 'image' }, userInfoStore.userInfo!.token!)
    if (res.data) {
      const resData = JSON.parse(res.data)
      const uploadRes = await updateProfileAPI({
        nickname: userInfoStore.userInfo?.nickname || '',
        avatar: resData.data.fullurl,
      }, userInfoStore.userInfo!.token!)
      if ((uploadRes.data as any).code === 1) {
        userInfoStore.setUserInfo({
          ...userInfoStore.userInfo!,
          avatar: resData.data.fullurl,
        })
        uni.showToast({ title: '上传成功', icon: 'none' })
      }
      else {
        uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
      }
    }
    else {
      uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
    }
  }
  catch (err) {
    uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
  }
}, 1000)

async function handleSubmitProfileCompletion(e: any) {
  if (e.detail.value.nickname) {
    try {
      const res = await updateProfileAPI({
        nickname: e.detail.value.nickname,
        avatar: userInfoStore.userInfo?.avatar || '',
      }, userInfoStore.userInfo!.token!)
      if ((res.data as any).code === 1) {
        userInfoStore.setUserInfo({
          ...userInfoStore.userInfo!,
          nickname: e.detail.value.nickname,
        })
        isShowCompletionDialog.value = false
      }
      else {
        uni.showToast({ title: '修改失败', icon: 'none' })
      }
    }
    catch (err) {
      uni.showToast({ title: '修改失败，请稍后重试', icon: 'none' })
    }
  }
  else {
    uni.showToast({ title: '请输入昵称', icon: 'none' })
  }
}
</script>

<template>
  <!-- 背景颜色 -->
  <view class="absolute left-0 top-0 z-0 h-345rpx w-screen bg-#4999F7" />
  <view class="relative z-1">
    <Spacer height="54" />
    <!-- Profile START -->
    <view class="flex items-center justify-between pl-32rpx pr-74rpx">
      <view class="flex items-center" @tap="handleSetProfile">
        <image class="h-140rpx w-140rpx rounded-full" :src="userInfoStore.userInfo?.avatar || avatarPlaceholder" />
        <Spacer width="24" />
        <view>
          <view class="text-36rpx text-white font-semibold leading-50rpx">
            {{ userInfoStore.userInfo?.nickname || '请登录' }}
          </view>
          <Spacer height="12" />
          <view v-if="userInfoStore.userInfo?.token" class="inline border-1px border-white rounded-full border-solid px-18rpx py-8rpx text-28rpx text-white font-semibold leading-40rpx">
            {{ userInfoStore.userInfo?.is_team_reward ? '合伙人' : '用户' }}
          </view>
        </view>
      </view>
      <image v-if="userInfoStore.userInfo?.token" class="h-52rpx w-52rpx" src="@/static/images/profile/qrcode.png" @tap="handleTapQRCode" />
    </view>
    <!-- Profile END -->
    <Spacer height="76" />
    <!-- 容器 START -->
    <view class="rounded-t-40rpx bg-#F8F8F8 px-32rpx" :style="{ minHeight: 'calc(100vh - 270rpx)' }">
      <Spacer v-if="userInfoStore.userInfo?.token" height="48" />
      <view v-if="userInfoStore.userInfo?.is_team_reward" class="relative h-127rpx w-686rpx" @tap="handleViewDistribution">
        <image
          class="h-127rpx w-686rpx"
          src="@/static/images/profile/fenxiao_bg.png"
        />
        <view class="absolute bottom-0 left-0 right-0 top-0 flex flex-col justify-center px-48rpx">
          <Spacer height="12" />
          <view class="text-24rpx text-white leading-24rpx">
            本月分销收益
          </view>
          <Spacer height="12" />
          <view class="text-40rpx text-white font-bold leading-56rpx">
            ¥ {{ distributionMoney || '0' }} >
          </view>
        </view>
      </view>
      <Spacer v-if="userInfoStore.userInfo?.is_team_reward" height="20" />
      <view v-if="userInfoStore.userInfo?.token" class="flex items-center justify-between">
        <!-- 1 -->
        <view class="relative h-180rpx w-330rpx px-28rpx py-36rpx" @tap="handleViewPointsMall">
          <image class="absolute left-0 top-0 z-0 h-180rpx w-330rpx" src="@/static/images/home/grid_2.png" />
          <view class="relative z-1 text-28rpx text-#6A6CCB font-medium leading-40rpx">
            我的积分
          </view>
          <view class="relative z-1 text-48rpx text-#6A6CCB font-semibold leading-68rpx">
            {{ userInfoStore.userInfo?.score || '未知' }}
          </view>
        </view>
        <Spacer width="26" />
        <!-- 2 -->
        <view class="relative h-180rpx w-330rpx px-28rpx py-36rpx" @tap="handleViewMyCouponList">
          <image class="absolute left-0 top-0 z-0 h-180rpx w-330rpx" src="@/static/images/home/grid_3.png" />
          <view class="relative z-1 text-28rpx text-#AE3037 font-medium leading-40rpx">
            我的优惠券
          </view>
          <view class="relative z-1 text-48rpx text-#AE3037 font-semibold leading-68rpx">
            {{ myCouponCount }}
          </view>
        </view>
      </view>
      <Spacer height="48" />
      <!-- 标题 START -->
      <Title>其他服务</Title>
      <!-- 标题 END -->
      <Spacer height="24" />
      <!-- 图标网格 START -->
      <view class="grid grid-cols-4 gap-x-0 gap-y-16rpx rounded-20rpx bg-white px-24rpx py-48rpx">
        <view class="flex flex-col items-center" @tap="handleTapRecord">
          <image class="h-80rpx w-80rpx" src="@/static/images/profile/calendar.png" />
          <Spacer height="12" />
          <view class="text-28rpx text-#333333 font-medium leading-40rpx">
            我的预约
          </view>
        </view>
        <view class="flex flex-col items-center" @tap="handleTapRedeemRecord">
          <image class="h-80rpx w-80rpx" src="@/static/images/profile/gift.png" />
          <Spacer height="12" />
          <view class="text-28rpx text-#333333 font-medium leading-40rpx">
            兑换记录
          </view>
        </view>
        <view class="flex flex-col items-center" @tap="handleTapInviteRecord">
          <image class="h-80rpx w-80rpx" src="@/static/images/profile/mail.png" />
          <Spacer height="12" />
          <view class="text-28rpx text-#333333 font-medium leading-40rpx">
            邀请记录
          </view>
        </view>
        <view class="flex flex-col items-center" @tap="handleTapMedicalAdvice">
          <image class="h-80rpx w-80rpx" src="@/static/images/profile/doc.png" />
          <Spacer height="12" />
          <view class="text-28rpx text-#333333 font-medium leading-40rpx">
            医嘱信息
          </view>
        </view>
        <view class="flex flex-col items-center" @tap="handleTapCouponList">
          <image class="h-80rpx w-80rpx" src="@/static/images/profile/ticket.png" />
          <Spacer height="12" />
          <view class="text-28rpx text-#333333 font-medium leading-40rpx">
            领券中心
          </view>
        </view>
        <view class="flex flex-col items-center" @tap="handleTapOfficalAccount">
          <image class="h-80rpx w-80rpx" src="@/static/images/profile/wechat.png" />
          <Spacer height="12" />
          <view class="text-center text-nowrap text-28rpx text-#333333 font-medium leading-40rpx">
            关注公众号
          </view>
        </view>
        <view class="flex flex-col items-center" @tap="isShowDialog = true">
          <image class="h-80rpx w-80rpx" src="@/static/images/profile/phone.png" />
          <Spacer height="12" />
          <view class="text-28rpx text-#333333 font-medium leading-40rpx">
            电话客服
          </view>
        </view>
        <button open-type="contact" class="flex flex-col items-center bg-transparent" @contact="handleContact">
          <image class="h-80rpx w-80rpx" src="@/static/images/profile/service.png" />
          <Spacer height="12" />
          <view class="text-28rpx text-#333333 font-medium leading-40rpx">
            在线客服
          </view>
        </button>
        <view class="flex flex-col items-center" @tap="handleTapSettings">
          <image class="h-80rpx w-80rpx" src="@/static/images/profile/settings.png" />
          <Spacer height="12" />
          <view class="text-28rpx text-#333333 font-medium leading-40rpx">
            设置
          </view>
        </view>
      </view>
      <!-- 图标网格 START -->
    </view>
    <!-- 容器 END -->
  </view>
  <uv-overlay :show="isShowDialog" @tap="isShowDialog = false">
    <uv-transition mode="zoom-in" :show="isShowDialog">
      <view class="relative h-screen w-screen">
        <Dialog :icon="dialogIcon" title="请拨打售后客服电话" confirm-label="立即拨打" @cancel="isShowDialog = false" @confirm="handleCall">
          <template #content>
            <view class="text-60rpx text-#333333 leading-84rpx">
              {{ generalDataStore.generalData?.mobile }}
            </view>
          </template>
        </Dialog>
      </view>
    </uv-transition>
  </uv-overlay>
  <uv-overlay :show="isShowCompletionDialog" @tap="isShowCompletionDialog = false">
    <uv-transition mode="zoom-in" :show="isShowCompletionDialog">
      <view class="relative h-screen w-screen">
        <Dialog :icon="dialogIcon" title="请拨打售后客服电话" confirm-label="立即拨打" @cancel="isShowCompletionDialog = false">
          <template #all>
            <Spacer height="48" />
            <view class="text-center text-40rpx font-bold">
              温馨提示
            </view>
            <Spacer height="20" />
            <view class="text-center text-28rpx text-#999999 leading-40rpx">
              99%的用户选择使用微信头像和昵称
            </view>
            <Spacer height="20" />
            <form class="rounded-10rpx bg-white" @submit="handleSubmitProfileCompletion">
              <button
                open-type="chooseAvatar" :style="{ padding: 0, margin: 0, background: 'none' }"
                @chooseavatar="handleChooseAvatar"
              >
                <ListCell label="头像">
                  <image class="my-20rpx h-80rpx w-80rpx rounded-full" :src="userInfoStore.userInfo?.avatar" />
                </ListCell>
              </button>
              <Divider color="#F0F0F0" />
              <ListCell label="昵称">
                <input name="nickname" type="nickname" class="text-secondary h-116rpx rounded-10rpx bg-white text-right text-28rpx leading-28rpx" :value="userInfoStore.userInfo?.nickname">
              </ListCell>
              <Spacer height="20" />
              <button name="submit" form-type="submit" class="h-96rpx w-500rpx flex items-center justify-center rounded-50rpx bg-#4999F7 text-32rpx text-white font-bold leading-32rpx x-center" hover-class="bg-brand">
                确认完善
              </button>
            </form>
            <Spacer height="32" />
          </template>
        </Dialog>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'profile'
style:
  navigationBarTitleText: '我的'
layout: 'custom'
</route>
